package com.umeox.ota.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.abupdate.iot_libs.engine.otaStatus.OtaStatus;
import com.abupdate.iot_libs.engine.otaStatus.OtaStatusMgr;
import com.abupdate.trace.Trace;
import com.umeox.ota.R;
import com.umeox.ota.data.local.RecordData;
import com.umeox.ota.engine.FotaInitTask;
import com.umeox.ota.gloable.App;
import com.umeox.ota.ui.activity.MainActivity;
import com.umeox.ota.utils.ActivityCollector;


public class DownloadView extends RelativeLayout implements View.OnClickListener {

    private static final String TAG = "DownloadView";
    public OtaStatus otaStatusTemp = OtaStatus.IDLE;

    private ProgressBar mProgressBar;
    private ImageView mCheckIv;
    private TextView mDownloadTv;
    private TextView mUpdateStatusTv;
    private View mUpgradeRl;

    public DownloadView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }

    public DownloadView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        LayoutInflater.from(getContext()).inflate(R.layout.view_download, this);
        mProgressBar = (ProgressBar) findViewById(R.id.view_circle);
        mCheckIv = (ImageView) findViewById(R.id.iv_check);
        mDownloadTv = (TextView) findViewById(R.id.tv_download);
        mUpgradeRl = (View) findViewById(R.id.rl_upgrade);
        mUpdateStatusTv = (TextView) findViewById(R.id.tv_update_state);
        mCheckIv.setOnClickListener(this);
        mDownloadTv.setOnClickListener(this);
    }


    public void setActionClickListener(@Nullable OnActionClickListener l) {
        mListener = l;
    }

    public void onUseMobileNetWork(String errorMsg) {
        mUpdateStatusTv.setText(errorMsg);
        mCheckIv.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_download) {
            Trace.d(TAG,"tv_download clicked");
            if (mListener != null) {
                mListener.onUpgrade();
            }

        } else if (v.getId() == R.id.iv_check) {
            Trace.d(TAG,"iv_check clicked");
            if (mListener != null) {

                switch (otaStatusTemp) {
                    case DOWNLOADING:
                        mListener.onCancelDownload();
                        break;
                    case DOWNLOAD_PAUSE:
                    case DOWNLOAD_FAILED:
                        setVisibility(GONE);
                        break;
                    case CHECK_NEW_VERSION:
                        mListener.onDownload(false);
                        break;
                    case NEED_REBOOT:
                    default:


                }


            }
        }
    }

    private OnActionClickListener mListener;

    public void setProgress(Integer integer) {
        mProgressBar.setProgress(integer);
    }

    public interface OnActionClickListener {
        void onDownload(boolean useMobileNetwork);

        void onUpgrade();

        void onCancelDownload();
    }

    public class Status {
        /*
        查询本地版本
         */
        public static final int STATE_QUERYLOCALVERSION = 0;

        /*
        查询服务器新版本
         */
        public static final int STATE_QUERYNEWVERSION = 1;

        /*
        查询到新版本
         */
        public static final int STATE_NEWVERSION_READY = 2;

        /*
        下载中
         */
        public static final int STATE_DOWNLOADING = 3;

        /*
        下载暂停
         */
        public static final int STATE_PAUSEDOWNLOAD = 4;

        /*
        下载完成
         */
        public static final int STATE_DLPKGCOMPLETE = 5;

        /*
        检测中
         */
        public static final int STATE_CHECKING = 6;

        /*
        取消下载
         */
        public static final int STATE_CANCELDOWNLOAD = 7;

        /*
         下载失败
          */
        public static final int STATE_FAILEDDOWNLOAD = 9;


        /*
        升级
         */
        public static final int STATE_UPGRADE = 8;

        /*
        升级失败
         */
        public static final int STATE_FAILUPGRADE = 10;

        /**
         * 升级中
         */
        public static final int STATE_UPGRADING = 11;

        /**
         * 升级成功
         */
        public static final int STATE_UPGRADE_SUCCESS = 12;

        /**
         * need reboot
         */
        public static final int STATE_NEED_REBOOT = 13;
    }


    public void setStatus(OtaStatus status) {
        Trace.d(TAG, "setStatus() :" + status);
        if (status == null) {
            return;
        }

        otaStatusTemp = status;
        switch (status) {
            case IDLE:
                refreshStatus(Status.STATE_QUERYNEWVERSION);
                break;

            case CHECKING:
                refreshStatus(Status.STATE_CHECKING);
                break;


            case UPGRADING:
                refreshStatus(Status.STATE_UPGRADING);
                break;

            case DOWNLOADING:
                refreshStatus(Status.STATE_DOWNLOADING);
                break;

            case UPGRADE_PAUSE:
            case DOWNLOAD_FINISHED:

                refreshStatus(Status.STATE_DLPKGCOMPLETE);
                break;
            case CHECK_NEW_VERSION:
            case DOWNLOAD_PAUSE:
            case DOWNLOAD_FAILED:
                refreshStatus(Status.STATE_NEWVERSION_READY);
                break;

            case UPGRADE_FAIL:
                refreshStatus(Status.STATE_FAILUPGRADE);
                break;

            case UPGRADE_SUCCESS:
                refreshStatus(Status.STATE_UPGRADE_SUCCESS);
                break;

            case NEED_REBOOT:
                refreshStatus(Status.STATE_NEED_REBOOT);
                break;

            default:
                break;
        }
    }


    public void setProgress(View view, int progress) {
        if (!FotaInitTask.isCompleted()) {
            Trace.d(TAG, "Init not completed");
            return;
        }
        OtaStatus otaStatus = OtaStatusMgr.getInstance().getCurStatus();
        Trace.d(TAG, "ota status: " + otaStatus.name() + ", progress: " + progress);
        Trace.d(TAG, "otaStatusTemp: " + otaStatusTemp.name() + ", progress: " + progress);
        switch (otaStatus) {
            case DOWNLOADING:
                if (progress <= 0) {
                    if (RecordData.downloadProgress > 0) {
                        progress = RecordData.downloadProgress;
                    } else {
                        progress = 0;
                    }
                }
                if (otaStatusTemp != OtaStatus.DOWNLOADING) {
                    progress = 0;
                }
                mDownloadTv.setText(progress + "%");
                mProgressBar.setProgress(progress);
                break;

            case UPGRADING:
                if (progress <= 0) {
                    if (RecordData.upgradeProgress > 0) {
                        progress = RecordData.upgradeProgress;
                    } else {
                        progress = 0;
                    }
                }
                mDownloadTv.setText(progress + "%");
                mProgressBar.setProgress(progress);
                break;

            case CHECKING:
                if (otaStatusTemp == OtaStatus.IDLE) {
                    mProgressBar.setProgress(0);
                } else {
                    mProgressBar.setProgress(10);
                }
                break;

            case IDLE:
                if (otaStatusTemp == OtaStatus.UPGRADING) {
                    mDownloadTv.setText(0 + "%");
                }
                mProgressBar.setProgress(0);
                break;

            case DOWNLOAD_FINISHED:
            case CHECK_NEW_VERSION:
                if (otaStatusTemp == OtaStatus.UPGRADING
                        || otaStatusTemp == OtaStatus.DOWNLOADING) {
                    mDownloadTv.setText("0%");
                    mProgressBar.setProgress(0);
                } else {
                    mProgressBar.setProgress(100);
                }
                break;
            case DOWNLOAD_PAUSE:
                mDownloadTv.setText("0%");
                mProgressBar.setProgress(0);
                break;
            case UPGRADE_SUCCESS:
            case UPGRADE_FAIL:
            case DOWNLOAD_FAILED:
            case UPGRADE_PAUSE:
            case NEED_REBOOT:
                mProgressBar.setProgress(100);
                break;
            default:
                mProgressBar.setProgress(10);
                break;
        }
    }

    public void refreshStatus(int status) {
        if (!FotaInitTask.isCompleted()) {
            Trace.d(TAG, "Init not completed");
            return;
        }
        switch (status) {
            case Status.STATE_QUERYNEWVERSION:
            case Status.STATE_FAILUPGRADE:
                Trace.d(TAG, "refreshStatus() STATE_QUERY_NEW_VERSION");
                refreshView(true, 100, false, GONE, GONE, App.sCx.getString(R.string.update_last_version), GONE, null);
                break;

            case Status.STATE_CHECKING:
                //检测版本中
                Trace.d(TAG, "refreshStatus() STATE_CHECKING");
                refreshView(false, 10, true, GONE, GONE, App.sCx.getString(R.string.update_checking), GONE, null);
                break;

            case Status.STATE_NEWVERSION_READY:
                //检测到新版本，可以点击下载
                Trace.d(TAG, "refreshStatus() STATE_NEW_VERSION_READY");
                setVisibility(View.GONE);
                break;

            case Status.STATE_CANCELDOWNLOAD:
                //取消下载
                Trace.d(TAG, "refreshStatus() STATE_CANCEL_DOWNLOAD");
                refreshView(false, 100, false, VISIBLE, GONE, App.sCx.getString(R.string.download_pause), GONE, R.drawable.ic_done_selector);
                break;

            case Status.STATE_DOWNLOADING:
                //下载中，可以点击取消下载按钮
                Trace.d(TAG, "refreshStatus() STATE_DOWNLOADING");
                refreshView(false, -1, false, VISIBLE, GONE, App.sCx.getString(R.string.downloading), GONE, R.drawable.ic_download_pause_selector);
                break;

            case Status.STATE_DLPKGCOMPLETE:
                setVisibility(VISIBLE);
                //下载完成，可以点击升级
                Trace.d(TAG, "refreshStatus() STATE_DLPKG_COMPLETE");
                refreshView(true, 100, false, GONE, VISIBLE, App.sCx.getString(R.string.download_finish), GONE, null);
                break;

            case Status.STATE_FAILEDDOWNLOAD:
                //下载失败
                Trace.d(TAG, "refreshStatus() STATE_FAILED_DOWNLOAD");
                refreshView(true, 100, false, VISIBLE, GONE, App.sCx.getString(R.string.download_pause), GONE, R.drawable.icon_check);
                break;

            case Status.STATE_UPGRADE:
            case Status.STATE_UPGRADING:
                //升级中
                Trace.d(TAG, "refreshStatus() STATE_UPGRADE");
                refreshView(false, -1, false, INVISIBLE, GONE, App.sCx.getString(R.string.updating), VISIBLE, null);

                break;
            case Status.STATE_UPGRADE_SUCCESS:
                Trace.d(TAG, "refreshStatus() STATE_UPGRADE_SUCCESS");
                refreshView(true, 100, false, VISIBLE, 0, App.sCx.getString(R.string.update_success), GONE, R.drawable.ic_done_selector);
                break;
            case Status.STATE_NEED_REBOOT:
                Trace.d(TAG, "refreshStatus() STATE_NEED_REBOOT");
                refreshView(true, 100, false, VISIBLE, GONE, App.sCx.getString(R.string.click_reboot), INVISIBLE, R.drawable.icon_check);
                MainActivity mainActivity = ActivityCollector.getActivity(MainActivity.class);
                if (mainActivity != null) {
                    mainActivity.createChooseAbupdateDialog();
                }
                break;
            default:
                break;
        }
    }

    public void showUpgrading() {

        Trace.d(TAG, "showUpgrading()");
        refreshView(false, 10, true, INVISIBLE, 0, App.sCx.getString(R.string.updating), GONE, null);
    }

    public void showDownloadPrepare() {
        Trace.d(TAG, "show Download Prepare");
        refreshView(false, 10, true, INVISIBLE, 0, App.sCx.getString(R.string.download_prepare), GONE, null);
    }

    public void showQueryLocalInfo() {
        Trace.d(TAG, "show Query Local Info");
        refreshView(false, 0, false, INVISIBLE, 0, App.sCx.getString(R.string.tips_fota_loading), GONE, null);
    }

    public void refreshView(boolean viewEnable, int progress, boolean needAnim, int checkVisibility, int installVisible, @Nullable String tips, int progressVisibility, @Nullable Integer resId) {
        mUpgradeRl.setVisibility(progressVisibility);
        mUpdateStatusTv.setText(tips);
        mCheckIv.setVisibility(checkVisibility);
        mDownloadTv.setVisibility(installVisible);
        if (resId!=null){
            mCheckIv.setImageResource(resId);
            mCheckIv.setClickable(true);
        } else {
            mCheckIv.setClickable(false);
        }
    }

    public void resetProgress() {
        mProgressBar.setProgress(0);
    }
}
